#!/bin/bash
set -e
set -x

# 参数默认值
repoDir=/mnt/cache/linglong-builder
repoName=stable
repoUrl=https://mirror-repo-linglong.deepin.com

# 解析参数
while test $# -gt 0; do
  case $1 in
    *-outdir)
      outdir="$2"
      shift
    ;;
    *-repo-dir)
      repodir="$2"
      shift
    ;;
    *-repo-url)
      repoUrl="$2"
      shift
    ;;
    *-repo-name)
      repoName="$2"
      shift
    ;;
    *)
      echo "Unknown parameter $1." >&2
      exit 1
    ;;
  esac
  shift
done

# 加锁，只允许单例运行
(
echo "Trying to acquire lock..."
flock 9
echo "Lock acquired. Executing commands under lock..."
# 生成builder配置
mkdir .ll-builder
echo "repo: $repoDir
version: 1" > .ll-builder/config.yaml
# 生成repo配置
mkdir -p $repoDir
echo "version: 1
defaultRepo: $repoName
repos:
  $repoName: $repoUrl" > $repoDir/config.yaml
# 清理旧的layers
rm -rf $repoDir/layers || true
# 下载base、runtime和sources
QT_LOGGING_RULES='*.debug=true' ll-builder build --skip-run-container
# 打包sources
tar -zcf "$outdir/layers.tar.gz" -C "$repoDir" "layers"
# 打包runtime
tar -zcf "$outdir/linglong.tar.gz" linglong
rm -r linglong
) 9>$repoDir/obs-linglong-service.lock
